package com.aiti.lulian.service.newCard;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.lulian.entity.newCard.CardEnterpriseUserCurrentUse;
import com.aiti.lulian.mapper.newCard.CardEnterpriseUserCurrentUseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * description:
 * auth fcb
 * date 2025-09-26 11:03
 **/
@Service
@Slf4j
public class CardEnterpriseUserCurrentUseService extends ServiceImpl<CardEnterpriseUserCurrentUseMapper, CardEnterpriseUserCurrentUse> {

    /**
     * 查询当前用户选中的企业名片
     * @param enterpriseId
     * @param userId
     * @return
     */
    public CardEnterpriseUserCurrentUse queryCardEnterpriseUserCurrentUse(String enterpriseId, String userId) {
        return baseMapper.queryCardEnterpriseUserCurrentUse(enterpriseId, userId);
    }

    /**
     * 添加用户正在使用名片
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCardEnterpriseUserCurrentUse(CardEnterpriseUserCurrentUse cardEnterpriseUserCurrentUse) {
        if(StrUtil.isBlank(cardEnterpriseUserCurrentUse.getEnterpriseId()) || StrUtil.isBlank(cardEnterpriseUserCurrentUse.getUserId()) || StrUtil.isBlank(cardEnterpriseUserCurrentUse.getCardId())) {
            log.warn("添加用户正在使用名片，参数错误");
            return;
        }
        CardEnterpriseUserCurrentUse existCurrentUse = baseMapper.queryCardEnterpriseUserCurrentUse(cardEnterpriseUserCurrentUse.getEnterpriseId(), cardEnterpriseUserCurrentUse.getUserId());
        if(existCurrentUse != null) {
            existCurrentUse.setCardId(cardEnterpriseUserCurrentUse.getCardId());
            this.baseMapper.updateById(existCurrentUse);
            return;
        }
        CardEnterpriseUserCurrentUse po = new CardEnterpriseUserCurrentUse();
        po.setBaseId(IdUtil.simpleUUID());
        po.setEnterpriseId(cardEnterpriseUserCurrentUse.getEnterpriseId());
        po.setUserId(cardEnterpriseUserCurrentUse.getUserId());
        po.setCardId(cardEnterpriseUserCurrentUse.getCardId());
        this.baseMapper.insert(po);
    }

    /**
     * 更新用户正在使用名片
     * @param baseId
     * @param cardId
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCardEnterpriseUserCurrentUse(String baseId, String cardId) {
        if(StrUtil.isBlank(baseId) || StrUtil.isBlank(cardId)) {
            log.warn("更新用户正在使用名片，参数错误");
            return;
        }
        CardEnterpriseUserCurrentUse cardEnterpriseUserCurrentUse = new CardEnterpriseUserCurrentUse();
        cardEnterpriseUserCurrentUse.setBaseId(baseId);
        cardEnterpriseUserCurrentUse.setCardId(cardId);
        this.baseMapper.updateById(cardEnterpriseUserCurrentUse);
    }

}
